package com.ysg.http;

import android.content.Context;
import android.util.Log;
import com.ysg.base.BaseApplication;
import com.ysg.http.cookie.CookieJarImpl;
import com.ysg.http.cookie.store.PersistentCookieStore;
import com.ysg.http.data.ApiService;
import com.ysg.http.interceptor.CacheInterceptor;
import com.ysg.http.interceptor.TokenInterceptor;
import com.ysg.http.interceptor.logging.Level;
import com.ysg.http.interceptor.logging.LoggingInterceptor;
import com.ysg.utils.YConfigUtil;
import com.ysg.utils.YSPUtils;
import com.ysg.utils.YStringUtil;
import java.io.File;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.Cache;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.internal.platform.Platform;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * RetrofitClient封装单例类, 实现网络请求
 */
public class RetrofitClient {
    //超时时间
    private static final int DEFAULT_TIMEOUT = 20;
    //缓存时间
    private static final int CACHE_TIMEOUT = 10 * 1024 * 1024;

    private static Context mContext = BaseApplication.getContext();
    private static OkHttpClient okHttpClient;
    private static Retrofit retrofit;
    private Cache cache = null;
    private File httpCacheDirectory;

    private static class SingletonHolder {
        private static RetrofitClient INSTANCE = new RetrofitClient();
    }

    public static RetrofitClient getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private RetrofitClient() {
        if (httpCacheDirectory == null) {
            httpCacheDirectory = new File(mContext.getCacheDir(), "goldze_cache");
        }

        try {
            if (cache == null) {
                cache = new Cache(httpCacheDirectory, CACHE_TIMEOUT);
            }
        } catch (Exception e) {
        }
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
        okHttpClient = RetrofitUrlManager.getInstance().with(new OkHttpClient.Builder())
                .cookieJar(new CookieJarImpl(new PersistentCookieStore(mContext)))
                .addInterceptor(new TokenInterceptor())
//                .addInterceptor(new BaseInterceptor(headers))
                .addInterceptor(new CacheInterceptor(mContext))
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                .addInterceptor(new LoggingInterceptor
                        .Builder()//构建者模式
                        .loggable(true) //是否开启日志打印
                        .setLevel(Level.BASIC) //打印的等级
                        .log(Platform.INFO) // 打印类型
                        .request("Request") // request的Tag
                        .response("Response")// Response的Tag
                        .build()
                )
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS))
                // 这里你可以根据自己的机型设置同时连接的个数和时间，我这里8个，和每个保持时间为10s
                .build();

        retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(getBaseUrl())
                .build();
    }

    public <T> T create(final Class<T> service) {
        if (service == null) {
            throw new RuntimeException("Api service is null!");
        }
        return retrofit.create(service);
    }


    public static <T> T execute(Observable<T> observable, Observer<T> subscriber) {
        observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
        return null;
    }

    /**
     * 设置基地址
     */
    public void setBaseUrl(String baseUrl){
        Log.e("baseUrl", ""+baseUrl);
        if (YStringUtil.isNotEmpty(baseUrl) && !ApiService.userLocalUrl){
            RetrofitUrlManager.getInstance().setGlobalDomain(baseUrl);
//            saveBaseUrl(baseUrl);
        }
    }

    /**
     * 保存基地址
     */
    public void saveBaseUrl(String baseUrl){
        YSPUtils.getInstance().saveBaseUrl(baseUrl);
    }

    /**
     * 获取基地址
     */
    private String getBaseUrl(){
//        String baseUrl = YSPUtils.getInstance().getBaseUrl();
        String baseUrl = YConfigUtil.getBaseUrl();
        if (YStringUtil.isEmpty(baseUrl)){
            baseUrl = ApiService.baseUrl;
        }
        return baseUrl;
    }
}
